package com.test.mchelepesa.activity_fragment_rice.fragment_rice;

import static com.test.mchelepesa.activity_fragment_rice.loan_rice.LoanMainActivity_rice.reviewNoticeFlag;
import static com.test.mchelepesa.activity_fragment_rice.loan_rice.LoanMainActivity_rice.loaningNoticeFlag;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.test.mchelepesa.R;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseLoanFragment_rice;
import com.test.mchelepesa.bean_rice.StaticConfig_rice;
import com.test.mchelepesa.bean_rice.config_info_rice.AppShowInfo_rice;
import com.test.mchelepesa.bean_rice.process_rice.ProcessInfo_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.BankAccountList_rice;
import com.test.mchelepesa.bean_rice.user_info_rice.LoanApplyDetailInfo_rice;
import com.test.mchelepesa.constant_rice.Constant_rice;
import com.test.mchelepesa.dialog_rice.BindAccountDialog_rice;
import com.test.mchelepesa.dialog_rice.BindChannelDialog_rice;
import com.test.mchelepesa.dialog_rice.DeleteAccountDialog_rice;
import com.test.mchelepesa.dialog_rice.NoticeDialog_rice;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpManager_rice;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class LoanWaitFragment_rice extends BaseLoanFragment_rice {

    private ImageView imageIv;
    private TextView titleTv, textTv;
    private View tipsView;

    private TextView loanAmountTv;
    private TextView loanTermTv;
    private View showAccountView;

    private TextView tipsTv;

    private TextView accountNumTv;

    private static boolean rateDoalogFlag = true;

    private View specialAccountsView;
    private LinearLayout specialAccountGroup;
    private View addAccountView;

    public boolean addBindFlag = false;
    public String bindAccountOldChannel = "";
    public String bindAccountMobile = "";
    public String bindAccountNewChannel = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_loan_wait_rice, container, false);
        init(view);
        return view;
    }

    @SuppressLint("SetTextI18n")
    private void init(View view){

        Button refreshStatusBtn = view.findViewById(R.id.fragment_loan_wait_btn_refresh_status);
        imageIv = view.findViewById(R.id.fragment_loan_wait_iv_image);
        titleTv = view.findViewById(R.id.fragment_loan_wait_tv_title);
        textTv = view.findViewById(R.id.fragment_loan_wait_tv_text);
        loanAmountTv = view.findViewById(R.id.fragment_loan_wait_tv_loan_amount);
        loanTermTv = view.findViewById(R.id.fragment_loan_wait_tv_loan_term);
        showAccountView = view.findViewById(R.id.fragment_loan_wait_view_show_account);
        accountNumTv = view.findViewById(R.id.fragment_loan_wait_tv_show_account_num);
        specialAccountsView = view.findViewById(R.id.fragment_loan_wait_view_special_accounts);
        specialAccountGroup = view.findViewById(R.id.fragment_loan_wait_layout_special_account_group);
        addAccountView = view.findViewById(R.id.fragment_loan_wait_view_add_account);
        tipsView = view.findViewById(R.id.fragment_loan_wait_view_tips);
        tipsTv = view.findViewById(R.id.fragment_loan_wait_tv_tips);

        initLicense(
                view.findViewById(R.id.fragment_loan_wait_view_license),
                view.findViewById(R.id.fragment_loan_wait_license_logo),
                view.findViewById(R.id.fragment_loan_wait_license_company_name)
        );

        refreshStatusBtn.setOnClickListener(v -> HttpManager_rice.getInstance().requestUserProcess());

        //放款中
        if (ProcessInfo_rice.getInstance().isOrderLoaning()){
            imageIv.setBackgroundResource(R.drawable.img_loan_loaning);
            titleTv.setText(getString(R.string.fragment_loan_loaning_title));
            textTv.setText(getString(R.string.fragment_loan_loaning_text));
            tipsView.setVisibility(View.GONE);
            pageTag_rice = "LOAN_LOANING_FRAGMENT";
        }else {
            imageIv.setBackgroundResource(R.drawable.img_loan_review);
            titleTv.setText(getString(R.string.fragment_loan_review_title));
            textTv.setText(getString(R.string.fragment_loan_review_text));
            tipsView.setVisibility(View.VISIBLE);
            pageTag_rice = "LOAN_REVIEWING_FRAGMENT";
        }

        if (!TextUtils.isEmpty(AppShowInfo_rice.getInstance().getTransferDelayImportant())){
            tipsTv.setVisibility(View.VISIBLE);
            tipsTv.setText(AppShowInfo_rice.getInstance().getTransferDelayImportant());
        }else tipsTv.setVisibility(View.GONE);

        if (StaticConfig_rice.isSpecialBindAccount()){
            showAccountView.setVisibility(View.GONE);
            specialAccountsView.setVisibility(View.VISIBLE);
            addAccountView.setOnClickListener(v -> {
                HttpManager_rice.getInstance().saveUserBuriedPoint("REVIEW_ADD_ACCOUNT_CLICK");
                new BindAccountDialog_rice(requireContext(),(mobile,channel) -> {
                    this.bindAccountMobile = mobile;
                    this.bindAccountOldChannel = channel;
                }).show();
            });
        }else {
            showAccountView.setVisibility(View.VISIBLE);
            specialAccountsView.setVisibility(View.GONE);
        }

        HttpManager_rice.getInstance().requestLoanApplyDetail();

    }

    @SuppressLint("SetTextI18n")
    public void onLoanApplyDetailResponse(){

        String currency = LoanApplyDetailInfo_rice.getInstance().getCurrency();

        loanAmountTv.setText(StaticConfig_rice.getMoneyUnit(currency)+" "+ LoanApplyDetailInfo_rice.getInstance().getAmount());
        loanTermTv.setText(LoanApplyDetailInfo_rice.getInstance().getDays()+" "+getString(R.string.word_days));

        if (StaticConfig_rice.Select_Country.equalsIgnoreCase(Constant_rice.Country_Ghana)) accountNumTv.setText(LoanApplyDetailInfo_rice.getInstance().getWalletMobile());
        else accountNumTv.setText(LoanApplyDetailInfo_rice.getInstance().getBankAccount());

        if (StaticConfig_rice.isSpecialBindAccount()) HttpManager_rice.getInstance().fetchBankAccount();
        else if (rateDoalogFlag){
            rateDoalogFlag = false;
            HttpManager_rice.getInstance().fetchStarWindowConfig();
        }else {

            if (ProcessInfo_rice.getInstance().isOrderLoaning()){
                String notice = AppShowInfo_rice.getInstance().getLoaningNotice();
                if (loaningNoticeFlag && !TextUtils.isEmpty(notice)){
                    loaningNoticeFlag = false;
                    new NoticeDialog_rice(requireContext(),notice).show();
                }
            }else {
                String notice = AppShowInfo_rice.getInstance().getReviewNotice();
                if (reviewNoticeFlag && !TextUtils.isEmpty(notice)){
                    reviewNoticeFlag = false;
                    new NoticeDialog_rice(requireContext(),notice).show();
                }
            }

        }

    }

    public void updateSpecialAccounts(){

        specialAccountGroup.removeAllViews();

        ArrayList<BankAccountList_rice.Account> accountList = BankAccountList_rice.getInstance().getBankAccountList();

        int count = 0;

        for (int i = accountList.size()-1;i>=0;i--){

            BankAccountList_rice.Account account = accountList.get(i);

            count++;

            View item = View.inflate(requireContext(),R.layout.item_account,null);

            TextView titleTv = item.findViewById(R.id.item_account_title);
            ImageView logoIv = item.findViewById(R.id.item_account_iv_logo);
            TextView channelTv = item.findViewById(R.id.item_account_tv_channel);
            TextView mobileTv = item.findViewById(R.id.item_account_tv_mobile);
            View deleteView = item.findViewById(R.id.item_account_delete);

            if (count>1) titleTv.setText(getString(R.string.bind_account_mobile_wallet,count));

            String logoUrl = account.getWalletLogo();
            if (!TextUtils.isEmpty(logoUrl)){
                new Thread(() -> {
                    try {
                        URL url = new URL(logoUrl);
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setConnectTimeout(4995);
                        connection.setRequestMethod("GET");
                        if (connection.getResponseCode()==200){
                            InputStream inputStream = connection.getInputStream();
                            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                            requireActivity().runOnUiThread(() -> logoIv.setImageBitmap(bitmap));
                        }
                    }catch (Exception e){
                        StringUtil_rice.printException(e);
                    }
                }).start();
            }

            channelTv.setText(account.getWalletDesc());
            mobileTv.setText(account.getWalletMobile());

            deleteView.setOnClickListener(v -> {
                HttpManager_rice.getInstance().saveUserBuriedPoint("ACCOUNT_INFO_DELETE_ACCOUNT_CLICK",account.getWalletDesc()+" "+account.getWalletMobile());
                new DeleteAccountDialog_rice(requireContext(),account).show();
            });

            specialAccountGroup.addView(item);

        }

        while (count<2){

            count++;

            View item = View.inflate(requireContext(),R.layout.item_bind_account_edit,null);

            TextView titleTv = item.findViewById(R.id.edit_account_title);

            if (count>1) titleTv.setText(getString(R.string.bind_account_mobile_wallet,count));

            int finalCount = count;
            item.findViewById(R.id.edit_account_view_click).setOnClickListener(v -> {
                HttpManager_rice.getInstance().saveUserBuriedPoint("ACCOUNT_INFO_EDIT_CLICK",String.valueOf(finalCount));
                new BindAccountDialog_rice(requireContext(),(mobile, channel) -> {
                    this.bindAccountMobile = mobile;
                    bindAccountOldChannel = channel;
                }).show();
            });

            specialAccountGroup.addView(item);

        }

        if (addBindFlag && !TextUtils.isEmpty(bindAccountOldChannel)  && !TextUtils.isEmpty(bindAccountNewChannel) && !TextUtils.isEmpty(bindAccountMobile)){

            AppShowInfo_rice.WalletChannel channel = AppShowInfo_rice.getInstance().findChannelByValue(bindAccountNewChannel);

            if (channel!=null) new BindChannelDialog_rice(requireContext(),bindAccountMobile,bindAccountOldChannel,channel).show();

            addBindFlag = false;
            bindAccountOldChannel = "";
            bindAccountNewChannel = "";
            bindAccountMobile = "";

        }else if (rateDoalogFlag){
            rateDoalogFlag = false;
            HttpManager_rice.getInstance().fetchStarWindowConfig();
        }

    }

}